/**
 * Created by Freeman on 2016/8/4.
 */

import {push} from 'react-router-redux'
import * as types from '../constants/ActionTypes'
import api from '../api'
import {showMsg} from './other'
import {getCookie,setCookie,signOut} from '../utils/authService'
function loginSuccess(token) {
    return {
        type:types.LOGIN_SUCCESS,
        token:token
    }
}

export const getUserInfo = (token=getCookie('token')) =>{
    return {
        type:types.GET_USERINFO,
        promise:api.getMe({
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
    }
};

export function localLogin(userInfo) {
    return (dispatch,getState) =>{
        return api.localLogin(userInfo)
            .then(response => ({json:response.data,status:response.statusText}))
            .then(({json,status}) =>{
                if (status!=='OK'){
                    return dispatch(showMsg(json.data.error_msg || '登录失败'))
                }
                setCookie('token',json.token);
                dispatch(loginSuccess(json.token));
                dispatch(getUserInfo(json.token));
                dispatch(showMsg('登录成功,欢迎光临!','success'))
                dispatch(push('/'))
            }).catch(err =>{
                return dispatch(showMsg(err.response.data.error_msg || '登录失败'))
            })
    }
}
export function logout() {
    return dispatch =>{
        signOut();
        dispatch({type:types.LOGOUT_SUCCESS})
        dispatch(push('/'))
    }
}

function successUpdateUser(user) {
    return {
        type:types.UPDATE_USER_SUCCESS,
        user:user
    }
}

export function updateUser(userInfo) {
    return (dispatch,getState) =>{
        return api.mdUser(userInfo)
            .then(response => ({json: response.data, status: response.statusText}))
            .then(({json,status}) => {
                if (status!=='OK'){
                    return dispatch(showMsg(json.data && json.data.error_msg || '更新用户资料失败'))
                }
                dispatch(showMsg('更新用户资料成功','success'))
                return dispatch(successUpdateUser(json.data))
            }).catch(err =>{
                return dispatch(showMsg(err.response.data.error_msg || '更新用户资料失败'))
            })
    }
}

export function registerUser(userInfo) {
    return (dispatch,getState) =>{
        return api.register(userInfo)
            .then(response => ({json: response.data, status: response.statusText}))
            .then(({json,status}) => {
                if (status!=='OK'){
                    return dispatch(showMsg(json.data && json.data.error_msg || '用户注册失败'))
                }
                dispatch(showMsg('用户注册成功','success'));
                return dispatch(push('/login'))
            }).catch(err =>{
                return dispatch(showMsg(err.response.data.error_msg || '用户注册失败'))
            })
    }
}